package com.bankwel.j3d.model;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import com.bankwel.j3d.core.J3dMatrix;

public class Cube extends Object3d {

	private float edge;

	public Cube(J3dMatrix j3d, float edge) {
		super(j3d);
		this.edge = edge;
	}

	@Override
	public void draw(Graphics2D g2d) {
		// TODO
		Vector3d origin = new Vector3d(-edge / 2, -edge / 2, -edge / 2);
		Vector3d[] v = new Vector3d[8];
		v[0] = origin.transform(getJ3d());
		v[1] = origin.add(edge, 0, 0).transform(getJ3d());
		v[2] = origin.add(edge, edge, 0).transform(getJ3d());
		v[3] = origin.add(0, edge, 0).transform(getJ3d());
		v[4] = origin.add(0, 0, edge).transform(getJ3d());
		v[5] = origin.add(edge, 0, edge).transform(getJ3d());
		v[6] = origin.add(edge, edge, edge).transform(getJ3d());
		v[7] = origin.add(0, edge, edge).transform(getJ3d());

		Dot[] d = new Dot[8];
		for (int i = 0; i < 8; i++)
			d[i] = v[i].to2d();

		int hide = 0;
		for (int i = 0; i < 8; i++)
			if (v[i].getZ() < v[hide].getZ())
				hide = i;
		for (int i = 0; i < 8; i++)
			if (i != hide && v[i] == v[hide])
				hide = -1;

		Color color = g2d.getColor();

		g2d.setColor(Color.CYAN);

		fillPolygon(d, 0, 1, 2, 3, hide, g2d);
		fillPolygon(d, 0, 1, 5, 4, hide, g2d);
		fillPolygon(d, 1, 2, 6, 5, hide, g2d);
		fillPolygon(d, 2, 3, 7, 6, hide, g2d);
		fillPolygon(d, 3, 0, 4, 7, hide, g2d);
		fillPolygon(d, 4, 5, 6, 7, hide, g2d);

		g2d.setColor(Color.GRAY);

		drawLine(d, 0, 1, hide, g2d);
		drawLine(d, 1, 2, hide, g2d);
		drawLine(d, 2, 3, hide, g2d);
		drawLine(d, 3, 0, hide, g2d);

		drawLine(d, 4, 5, hide, g2d);
		drawLine(d, 5, 6, hide, g2d);
		drawLine(d, 6, 7, hide, g2d);
		drawLine(d, 7, 4, hide, g2d);

		drawLine(d, 0, 4, hide, g2d);
		drawLine(d, 1, 5, hide, g2d);
		drawLine(d, 2, 6, hide, g2d);
		drawLine(d, 3, 7, hide, g2d);

		g2d.setColor(color);
	}

	private void drawLine(Dot[] set, int from, int to, int exception, Graphics2D g) {
		if (from != exception && to != exception)
			g.drawLine((int) set[from].getX(), (int) set[from].getY(), (int) set[to].getX(), (int) set[to].getY());
		return;
	}

	private void fillPolygon(Dot[] set, int p1, int p2, int p3, int p4, int exception, Graphics2D g) {
		if (p1 != exception && p2 != exception && p3 != exception && p4 != exception) {
			Polygon p = new Polygon();
			p.addPoint((int) set[p1].getX(), (int) set[p1].getY());
			p.addPoint((int) set[p2].getX(), (int) set[p2].getY());
			p.addPoint((int) set[p3].getX(), (int) set[p3].getY());
			p.addPoint((int) set[p4].getX(), (int) set[p4].getY());
			g.fillPolygon(p);
		}
		return;
	}
}
